package com.zhentao.util;

import io.minio.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.util.UUID;

@Component
public class MinioUtils {

    private static final Logger log = LoggerFactory.getLogger(MinioUtils.class);

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.accessSecret}")
    private String accessSecret;

    @Value("${minio.bucketName}")
    private String bucketName;

    private MinioClient minioClient;

    @PostConstruct
    public void init() {
        try {
            // 初始化 MinioClient (使用 @PostConstruct 确保单例创建)
            minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, accessSecret)
                    .build();

            // 启动时检查存储桶是否存在，不存在则创建
            createBucketIfNotExists();

            log.info("MinIO 客户端初始化成功，Endpoint: {}", endpoint);
        } catch (Exception e) {
            log.error("MinIO 客户端初始化失败", e);
            throw new RuntimeException("MinIO 客户端初始化失败", e);
        }
    }

    private void createBucketIfNotExists() {
        try {
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                log.info("创建 MinIO 存储桶: {}", bucketName);
            }
        } catch (Exception e) {
            log.error("检查或创建存储桶失败", e);
            throw new RuntimeException("检查或创建存储桶失败", e);
        }
    }

    /**
     * 生成随机文件名
     */
    private String generateRandomFileName(String originalFileName) {
        if (originalFileName == null || originalFileName.isEmpty()) {
            return UUID.randomUUID().toString();
        }
        int dotIndex = originalFileName.lastIndexOf('.');
        String extension = dotIndex > 0 ? originalFileName.substring(dotIndex) : "";
        return UUID.randomUUID().toString() + extension;
    }

    /**
     * 上传文件到 MinIO
     * @return 文件访问 URL
     */
    public String uploadFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            log.warn("上传文件为空，直接返回");
            return null;
        }

        String objectName = generateRandomFileName(file.getOriginalFilename());
        String contentType = file.getContentType() != null ? file.getContentType() : "application/octet-stream";

        try (InputStream inputStream = file.getInputStream()) {
            // 使用 try-with-resources 确保流自动关闭

            // 上传文件
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(inputStream, file.getSize(), -1)
                    .contentType(contentType)
                    .build());

            String url = endpoint + "/" + bucketName + "/" + objectName;
            log.info( url);
            return url;

        } catch (Exception e) {
            log.error("文件上传失败: {}", objectName, e);
            throw new RuntimeException("文件上传失败", e);
        }
    }

    // 可添加其他方法如删除文件、获取文件等...
}
